package com.bawei.module_mine.login

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_common.base.utils.ToastUtils
import com.bawei.lib_common.observeWithLifecycle
import com.bawei.module_mine.MineActivity
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.ActivityModifyPassBinding
import com.bawei.module_mine.mine.MineViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

@AndroidEntryPoint
@Route(path = Router.Ui.ModifyPassActivity)
class ModifyPassActivity : BaseActivity<MineViewModel,ActivityModifyPassBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_modify_pass
    override val mViewModel: MineViewModel by viewModels()
    private var countdownJob: Job? = null // 用于取消协程
    private val mHandler = Handler(Looper.getMainLooper())// 用于延迟执行任务
    private var mCode:String = ""
    // 手机号正则表达式（匹配11位，1开头，第二位3-9）
    private val PHONE_REGEX = "^1[3-9]\\d{9}$".toRegex()

    override fun initView() {
        mBinding.viewmodel = mViewModel
        mBinding.lifecycleOwner = this
        initHeader()
    }
    private fun initHeader() {
        mBinding.loginHead.apply {
            loginHeadPen.visibility = View.GONE
            loginHeadHead.visibility = View.GONE
            loginHeadPlane.visibility = View.GONE
            loginHeadUsername.visibility = View.GONE
        }
    }

    override fun initListener() {
        mViewModel.requestModifyPassEvent.observeWithLifecycle(this, Lifecycle.State.STARTED){
            when(it){
                is Success -> {
                    setLoadingViewVisible(false)
                    //账号密码注册成功
                    ToastUtils.showLong(this@ModifyPassActivity,"修改成功,即将跳转登录页面")
                    //延迟跳转
                    mHandler.postDelayed({
                        ARouter.getInstance().build(Router.Ui.LoginActivity).withString(Router.Intent.EXTRA_PHONE,mViewModel.phone.value).withString(Router.Intent.EXTRA_PASSWORD,mViewModel.newPassword.value).navigation()
                    }, 1000)
                }
                is Loading -> {
                    setLoadingViewVisible(true)
                    //账号密码注册成功
                }
                is Failed -> {
                    setLoadingViewVisible(false)
                    ToastUtils.showLong(this@ModifyPassActivity,"修改失败,请检查手机号和新密码密码是否正确")
                }
                else ->{

                }
            }
        }
    }

    override fun initData() {
        mBinding.btnModifyPass.setOnClickListener {
            if (mBinding.username.text.toString().trim().isBlank()){
                ToastUtils.showLong(this@ModifyPassActivity,"手机号不可以为空")
                return@setOnClickListener
            }
            if (!mBinding.username.text?.matches(PHONE_REGEX)!!){
                ToastUtils.showLong(this@ModifyPassActivity,"请输入正确的手机号")
                return@setOnClickListener
            }
            if (mBinding.code.text.toString() != mCode){
                ToastUtils.showLong(this@ModifyPassActivity,"验证码错误")
                return@setOnClickListener
            }
           mViewModel.modifyPassword()
        }
        mBinding.getCode.setOnClickListener {
            startCountdown()
            generateAndShowRandomNumber()
        }
    }
    /**
     * 启动 60 秒倒计时
     */
    private fun startCountdown() {
        // 禁用按钮防止重复点击
        mBinding.getCode.isEnabled = false
        // 初始剩余时间（秒）
        var remainingTime = 60

        // 使用协程启动倒计时（生命周期感知）
        countdownJob = lifecycleScope.launch {
            while (remainingTime > 0) {
                // 更新 UI（必须在主线程）
                mBinding.getCode.text = formatTime(remainingTime)
                // 延迟 1 秒（协程挂起，不阻塞主线程）
                delay(1000)
                remainingTime--
            }

            // 倒计时结束后恢复 UI
            mBinding.getCode.isEnabled = true
            mBinding.getCode.text = "再次发送验证码"
        }
    }

    /**
     * 格式化时间为 "00:MM" 形式（如 60 → "01:00"）
     */
    private fun formatTime(seconds: Int): String {
        val minutes = seconds / 60
        val secs = seconds % 60
        return String.format("%02d:%02d", minutes, secs)
    }
    /**
     * 生成 6 位随机数并显示
     */
    private fun generateAndShowRandomNumber() {
        // 生成 100000 到 999999 之间的随机整数（包含两端）
        val randomNumber = Random.nextInt(100000, 1000000) // 注意：第二个参数是开区间，所以用 1000000
        mCode = randomNumber.toString().padStart(6, '0')
        // 显示结果（格式化为 6 位，不足补前导零）
        LoggerUtils.d("code",randomNumber.toString().padStart(6, '0'))
    }
    /**
     * 页面销毁时取消协程（防止内存泄漏）
     */
    override fun onDestroy() {
        super.onDestroy()
        countdownJob?.cancel() // 取消未完成的倒计时
        mHandler.removeCallbacksAndMessages(null)//  移除所有延迟任务
    }

}